package cn.juque.lucenecandy.core.handlers;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.juque.lucenecandy.bo.FieldBO;
import cn.juque.lucenecandy.bo.IndexBO;
import cn.juque.lucenecandy.core.base.BaseEntity;
import cn.juque.lucenecandy.core.enums.FieldFillEnum;
import cn.juque.lucenecandy.core.handlers.metaobject.IMetaObject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 注入公共字段自动填充,任选注入方式即可
 *
 * @author huangjinghua
 */

@Slf4j
public class EntityMetaObjectHandler {

    private static final List<IMetaObject> CUSTOM_FIELD_LIST = CollUtil.newArrayList();

    static {
        Set<Class<?>> classSet = ClassUtil.scanPackageBySuper(null, IMetaObject.class);
        classSet.forEach(c -> {
            IMetaObject metaObject = (IMetaObject) ReflectUtil.newInstanceIfPossible(c);
            CUSTOM_FIELD_LIST.add(metaObject);
        });
        classSet = ClassUtil.scanPackageBySuper("cn.juque.lucenecandy.core.handlers.metaobject.impl", IMetaObject.class);
        classSet.forEach(c -> {
            IMetaObject metaObject = (IMetaObject) ReflectUtil.newInstanceIfPossible(c);
            CUSTOM_FIELD_LIST.add(metaObject);
        });
    }

    /**
     * 填充
     *
     * @param fillEnum 操作
     * @param indexBO  索引信息
     * @param entity   T
     */
    public <T extends BaseEntity> void fill(FieldFillEnum fillEnum, IndexBO indexBO, T entity) {
        if (Objects.isNull(entity) || Objects.isNull(indexBO)) {
            return;
        }
        Map<String, FieldBO> fieldMap = indexBO.getFieldMap();
        fieldMap.forEach((k, v) -> {
            for (IMetaObject metaObject : CUSTOM_FIELD_LIST) {
                metaObject.invoke(fillEnum, entity, k, v);
            }
        });
    }
}
